package com.fw4j.configure;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.fw4j.configure.entity.ControllerConfigure;
import com.fw4j.configure.entity.Fw4jConfigure;
import com.fw4j.configure.entity.PoolConfigure;

public class XmlParse {
	private ControllerConfigure cc = null;
	private PoolConfigure pc = null;
	private Map<String,PoolConfigure> Pcmap = null;
	private boolean pool = false;
	
	private Fw4jConfigure fw4jCnfigure = new Fw4jConfigure();
	
	private static XmlParse instance = null;
	public static XmlParse getInstance(){
		if(instance == null){
			instance = new XmlParse();
		}
		return instance;
	}
	private XmlParse(){
		 InputStream in = ClassLoader.getSystemResourceAsStream("fw4j.xml");
		 SAXReader reader = new SAXReader();
		 try {
			Document doc = reader.read(in);
			this.element(doc.getRootElement());
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	private void element(Element el){
		Iterator it = el.elementIterator();
		while(it.hasNext()){
			el = (Element) it.next();
			if(el.getName().toLowerCase().equals("controller")){
				cc = new ControllerConfigure();
				fw4jCnfigure.setCconfigure(cc);
				cc.setValue(el.attributeValue("value"));
				this.element(el);
			}else if(el.getName().toLowerCase().equals("jdbc")){
				Pcmap = new HashMap<String,PoolConfigure>();
				pool = Boolean.parseBoolean(el.attributeValue("pool"));
				fw4jCnfigure.setPconfigure(Pcmap);
				this.element(el);
			}else if(el.getName().toLowerCase().equals("encoding")){
				cc.setEncoding(el.getTextTrim());
			}else if(el.getName().toLowerCase().equals("view")){
				cc.setView(el.getTextTrim());
			}else if(el.getName().toLowerCase().equals("pool")){
				pc = new PoolConfigure();
				pc.setDatabase(el.attributeValue("database"));
				pc.setPool(pool);
				Pcmap.put(pc.getDatabase(), pc);
				this.element(el);
			}else if(el.getName().toLowerCase().equals("url")){
				pc.setUrl(el.getTextTrim());
			}else if(el.getName().toLowerCase().equals("driver")){
				pc.setDriver(el.getTextTrim());
			}else if(el.getName().toLowerCase().equals("user")){
				pc.setUser(el.getTextTrim());
			}else if(el.getName().toLowerCase().equals("pwd")){
				pc.setPwd(el.getTextTrim());
			}else if(el.getName().toLowerCase().equals("outofdata")){
				pc.setOutOfData(Integer.parseInt(el.getTextTrim()));
			}else if(el.getName().toLowerCase().equals("monitortime")){
				pc.setMonitorTime(Integer.parseInt(el.getTextTrim()));
			}
			
		}
	}
	public Fw4jConfigure getFw4jCnfigure() {
		return fw4jCnfigure;
	}
}
